import ProTable from '@ant-design/pro-table';
import { Form } from '@ant-design/compatible';
import { Button, message, Icon, DatePicker, Input, Select, Modal, Spin } from 'antd';
import React, { useState, useRef, useEffect, useCallback } from 'react';
import '@ant-design/compatible/assets/index.css';
import { costdetail, exportCostbookdetail, queryCityInfo, markFlag, quickMarkFlag, summary} from '../service';
import { useRequest } from '@umijs/hooks';

import TotalModal from './totalModal'
import CustomExportModal from './customExportModal'
import styles from './index.less';

import moment from 'moment';
import AuthComponent from '@/components/Authorized/AuthComponent';

const { Option } = Select;
const { confirm } = Modal
// let hiddenData = null
let isFirst = true;

const DetailTable = () => {
  const { data: selectData } = useRequest(queryCityInfo);

  const [btnLoading, handleBtnLoading] = useState(false)
  // 切换清空搜索
//   useEffect(() => {
//     hiddenData = null
//   // eslint-disable-next-line react-hooks/exhaustive-deps
//   }, [])
  // 计算高度
  const [height, controlH] = useState(300);
  const [isCollapse, controlC] = useState(true);
  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 370);
    } else {
      controlH(document.body.clientHeight - 470);
    }
  }, [isCollapse])

  // 总计弹框
  const [totalModalVisible, handleTotalModalVisible] = useState(false);
  const [totalData, handleTotalData] = useState({});
  
  const [customExportModalVisible, handleCustomExportModalVisible] = useState(false);

  const [selectedRowKeys, handleSelectedRowKeys] = useState([]) // 勾选索引
  const [selectedRows, handleSelectedRows] = useState([]) // 勾选列

  const actionRef = useRef();
  const ref = useRef();

  const [inited, setInited] = useState(true)

  const [searchParams, setSearchParams] = useState('')

  const [exportFlag, handleExportFlag] = useState('')

  const formatFlightNo = (val) => {
    if (!val) {
      return '';
    } else if (val.length < 3 || /^\D/.test(val)) {
      return ''.toUpperCase.call(val);
    } else if (/^\d{2}/.test(val)) {
      return `3U${val}`;
    } else {
      return val;
    }
  }
  /**
   * 导出
   */
  const handleExport = () => {
    if (!exportFlag){
      message.error('表格数据为空')
      return false
    }
    handleBtnLoading(true)
    const hide = message.loading('正在导出');
    let res = exportCostbookdetail({...searchParams, columnFiledNames: []}).then(res=>{
      let blob = new Blob([res], {
        type: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      })
      let elink = document.createElement('a')
     let time=moment(Date.now()).format('YYYY-MM-DD HH_mm_ss')
      elink.download = '异常行李成本分析报表列表'+time+'.xls'
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      document.body.removeChild(elink)
      hide();
    handleBtnLoading(false)
      message.success('导出成功');
    }).catch(err => {
    handleBtnLoading(false)
      console.log(err)
    });
  }

  // 标记状态
  const changeFlag = async (rows, flag) => {
    let text = flag === '0' ? '取消标记' : '标记'
    handleBtnLoading(true)
    try {
      await markFlag({
        ids: rows.map(row => row.paxMainKey).toString(),
        status: flag
      });
      handleBtnLoading(false)
      message.success(text + '成功');
      return true;
    } catch (error) {
      handleBtnLoading(false)
      message.error(text + '失败，请重试！');
      return false;
    }
  }

  // 一键标记
  const quickMark = async () => {
    handleBtnLoading(true)
    try {
      await quickMarkFlag({...searchParams,receiveType: 1, flag: 1});
      handleBtnLoading(false)
      message.success('一键标记成功');
      return true;
    } catch (error) {
      handleBtnLoading(false)
      message.error('一键标记失败，请重试！');
      return false;
    }
  }
  // 总计
  const handleTotal = () => {
    handleBtnLoading(true)
    summary(searchParams).then(res => {
      handleTotalData(res)
      handleTotalModalVisible(true)
      handleBtnLoading(false)
    })
  }
  const handleCustomExport = () => {
    handleCustomExportModalVisible(true)
  }
  // 搜索
  const beforeSearchSubmit = useCallback(params =>{
    params['beginDate'] = params.beginDate ? params.beginDate.format('YYYY-MM-DD') : '';
    params['endDate'] = params.endDate ? params.endDate.format('YYYY-MM-DD') : '';
    // if (!isCollapse) {
    //   setSearchParams(params)
    //   return params
    // } else {
      if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '查 询') {
        if (Object.keys(params).indexOf('beginDate') === -1) {
          params.beginDate = ''
        }
        if (Object.keys(params).indexOf('endDate') === -1) {
          params.endDate = ''
        }

        setSearchParams({ ...params})
        return { ...params}
        
      } else if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
        isFirst = true;
        ref.current.setFieldsValue({
          beginDate: moment(),
          endDate: moment()
        })
        setSearchParams(params)
        return params
      }
    // }
  }, [isCollapse]);
  useEffect(() => {
    return () => {
      isFirst = true;
    }
  }, [])
  const columns = [
    {
      title: '航班起始日期',
      hideInTable: true,
      dataIndex: 'beginDate',
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '航班结束日期',
      hideInTable: true,
      dataIndex: 'endDate',
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '支付起始日期',
      hideInTable: true,
      dataIndex: 'payBeginDate',
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '支付结束日期',
      hideInTable: true,
      dataIndex: 'payEndDate',
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '财务标记',
      dataIndex: 'isFlag',
      width:120,
      key: 'isFlag',
      fixed: 'left',
      render: (_, record) => {
        return record.isFlag === '标记' ? <span>已标记</span> : ''
      },
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            mode="multiple"
            allowClear={true}
            placeholder="请选择"
          >
            <Option key='0'>未标记</Option>
            <Option key='1'>已标记</Option>
          </Select>
        );
      },
    },
    {
      title: '航班日期',
      dataIndex: 'flightDate',
      hideInSearch: true,
      width: 90,
      fixed: 'left'
    },
    {
      title: '航班号',
      width:90,
      dataIndex: 'flightNo',
      fixed: 'left',
      renderFormItem: (_, { type, defaultRender, ...rest }) => {
        return <Input 
          {...rest}
          onChange= {e => {
            e.target.value = formatFlightNo(e.target.value);
            rest.onChange(e.target.value)
          }}
          allowClear maxLength={6} placeholder="3U" />;
      }
    },
    {
      title: '起飞航站',
      dataIndex: 'org',
      initialValue: '', //缺个默认接口服务航站
      hideInTable: true,
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      title: '到达航站',
      dataIndex: 'dst',
      hideInTable: true,
      initialValue: '', //缺个默认接口服务航站
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      title: '起飞航站',
      dataIndex: 'orgName',
      hideInSearch: true,
      width: 100
    },
    {
      title: '到达航站',
      dataIndex: 'dstName',
      hideInSearch: true,
      width: 100
    },
    {
      title: '发生地',
      dataIndex: 'serviceCity',
      width: 120,
      initialValue: '', //缺个默认接口服务航站
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      title: '财务机型',
      dataIndex: 'flightModel',
      width:90,
      key: 'flightModel',
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            mode="multiple"
            allowClear={true}
            placeholder="请选择"
          >
            <Option key='A319'>A319</Option>
            <Option key='A320'>A320</Option>
            <Option key='A321'>A321</Option>
            <Option key='A330'>A330</Option>
            <Option key='A350'>A350</Option>
          </Select>
        );
      },
    },
    {
      title: '地区类别',
      dataIndex: 'flightType',
      width:90,
      key: 'flightType',
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            mode="multiple"
            allowClear={true}
            placeholder="请选择"
          >
            <Option key='D'>国内</Option>
            <Option key='I'>国际</Option>
          </Select>
        );
      },
    },
    {
      title: '原因',
      dataIndex: 'innerReason',
      width:160,
      hideInSearch: true,
    },
    {
      title: '补偿单号',
      dataIndex: 'orderId',
      width:160,
      hideInSearch: true,
    },
    {
      title: '补偿类型',
      dataIndex: 'luggageCompensationType',
      width:120,
      hideInSearch: true,
    },
    {
      title: '事故单号',
      dataIndex: 'accidentId',
      width: 120,
      hideInSearch: true
    },
    {
      title: '姓名',
      width: 120,
      dataIndex: 'paxName',
    },
    {
      title: '票号',
      width:160,
      dataIndex: 'tktNo',
    },
    {
      title: '授权金额',
      dataIndex: 'currentAmount',
      hideInSearch: true,
      width: 100,
    },
    {
      title: '支付金额',
      dataIndex: 'payAmount',
      hideInSearch: true,
      width: 100,
    },
    {
      title: '差异',
      dataIndex: 'difference',
      hideInSearch: true,
      width: 90,
    },
    {
      title: '领取状态',
      dataIndex: 'receiveType',
      width:100,
      key: 'receiveType',
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            mode="multiple"
            allowClear={true}
            placeholder="请选择"
          >
            <Option key='0'>未领取</Option>
            <Option key='2'>领取中</Option>
            <Option key='1'>已领取</Option>
          </Select>
        );
      },
    },
    {
      title: '财务状态',
      dataIndex: 'financialStatus',
      hideInSearch: true,
      width: 100,
    },
    {
      title: '申领单号',
      dataIndex: 'applyCode',
      width: 160,
    },
    {
      title: '支付状态',
      dataIndex: 'payStatus',
      width:100,
      key: 'payStatus',
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            mode="multiple"
            allowClear={true}
            placeholder="请选择"
          >
            <Option key='0'>未支付</Option>
            <Option key='1'>支付成功</Option>
            <Option key='2'>支付失败</Option>
            {/* <Option key='3'>处理中</Option> */}
          </Select>
        );
      },
    },
    {
      title: '审核状态',
      dataIndex: 'applyStatus',
      width:100,
      key: 'applyStatus',
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            mode="multiple"
            allowClear={true}
            placeholder="请选择"
          >
            <Option key='0'>待审核</Option>
            <Option key='1'>通过</Option>
            <Option key='2'>未通过</Option>
          </Select>
        );
      },
    },
    {
      title: '领取渠道',
      dataIndex: 'isScene',
      hideInTable: true,
      key: 'isScene',
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            mode="multiple"
            allowClear={true}
            placeholder="请选择"
          >
            <Option key='1'>现场</Option>
            <Option key='0'>事后</Option>
          </Select>
        );
      },
    },
    {
      title: '领取渠道',
      dataIndex: 'scene',
      hideInSearch: true,
      width: 100,
    },
    {
      title: '支付方式',
      dataIndex: 'payTypes',
      key: 'payTypes',
      hideInTable:true,
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            mode="multiple"
            allowClear={true}
            placeholder="请选择"
          >
            <Option key='0'>微信</Option>
            <Option key='1'>银联</Option>
            <Option key='4'>现金</Option>
            <Option key='2'>支付宝</Option>
          </Select>
        );
      },
    },
    {
      title: '支付方式',
      dataIndex: 'payType',
      hideInSearch: true,
      width: 100,
    },
    {
      title: '户名',
      dataIndex: 'accountName',
      hideInSearch: true,
      width: 120,
    },
    {
      title: '开户银行',
      dataIndex: 'bankName',
      hideInSearch: true,
      width: 160,
    },
    {
      title: '账号',
      dataIndex: 'moneyAccount',
      hideInSearch: true,
      width: 160,
    },
    {
      title: '支付日期',
      dataIndex: 'payDate',
      hideInSearch: true,
      width: 120,
    },
    {
      title: '支付时间',
      dataIndex: 'payTime',
      hideInSearch: true,
      width: 120,
    },
    {
      title: '支付流水号',
      dataIndex: 'returnOrderNo',
      hideInSearch: true,
      width: 120,
    },
    {
      title: '到期日',
      dataIndex: 'expiryDate',
      hideInSearch: true,
      width: 120
    },
    {
      title: '权限审批人职务及姓名',
      dataIndex: 'auditInfo',
      hideInSearch: true,
      width: 120
    },
  ];

  const tableSelectChange = (selectedRowKeys, selectedRows) =>{
    handleSelectedRowKeys(selectedRowKeys)
    handleSelectedRows(selectedRows)
  }

  const rowSelection = {
    selectedRowKeys,
    onChange: tableSelectChange,
  };
  return (
    <div>
      <Spin spinning={btnLoading}>
      <ProTable
        className={`${styles.luggageCharts} rest-pro-table-form-compact rest-pro-table-tab ${isCollapse?'':'collapse'}`}
        formRef={ref}
        options={{density: false, fullScreen:true, reload:false, setting:true}}
        scroll={{ x: 1300, y:height }}
        size='small'
        search={{
          onCollapse:val => {
            controlC(val);
            // if (!val && hiddenData) {
            //   ref.current.setFieldsValue({
            //     payBeginDate: hiddenData.payBeginDate,
            //     payEndDate: hiddenData.payEndDate,
            //     isFlag: hiddenData.isFlag,
            //     flightNo: hiddenData.flightNo,
            //     org: hiddenData.org,
            //     dst: hiddenData.dst,
            //     serviceCity: hiddenData.serviceCity,
            //     flightModel: hiddenData.flightModel,
            //     flightType: hiddenData.flightType,
            //     paxName: hiddenData.paxName,
            //     tktNo: hiddenData.tktNo,
            //     receiveType: hiddenData.receiveType,
            //     applyCode: hiddenData.applyCode,
            //     payStatus: hiddenData.payStatus,
            //     applyStatus: hiddenData.applyStatus,
            //     isScene: hiddenData.isScene,
            //     payTypes: hiddenData.payTypes,
            //   })
            // } else {
            //   hiddenData = ref.current.getFieldsValue()
            // }
          }
        }}
        headerTitle={
          <div>
            <span style={{ paddingRight: 10, fontWeight: "bold", color: "#000" }}>成本分析表</span>
          </div>
        }
        actionRef={actionRef}
        rowKey="id"
        rowSelection={rowSelection}
        toolBarRender={() => [
          <AuthComponent authCode="luggageCharts.cost.mark">
            <Button type="primary" onClick={() => {
              if (selectedRows.length === 0) {
                message.error("请选择需要标记的条目 ！")
              } else {
                let receiveFlag = ''
                selectedRows.forEach(element => {
                  if (element.receiveType !== '已领取' || element.isFlag === '标记') {
                    receiveFlag = true
                  }
                });
                if (receiveFlag) {
                  confirm({
                    title: '提示',
                    content: '只能选择‘未标记’并且领取状态为‘已领取’的条目',
                  })
                } else {
                  confirm({
                    title: '提示',
                    content: `共选择${selectedRows.length}条需要标记的条目，是否进行标记操作？`,
                    cancelText: '取消',
                    okText: '确认',
                    onOk: async () => {
                      const result = await changeFlag(selectedRows, '1')
                      if(result){
                        actionRef.current.reload();
                        handleSelectedRows([])
                        handleSelectedRowKeys([])
                      }
                    }
                  })
                }
              }
            }}>
              标记
            </Button>
          </AuthComponent>,
          <AuthComponent authCode="luggageCharts.cost.quickmark">
            <Button type="default" onClick={() => {
              confirm({
                title: '提示',
                content: '为了保持数据一致性，请页面查询完成后不要修改查询条件，否则可能会造成标记的条目与查询到的条目不一致！',
                cancelText: '取消',
                okText: '确认',
                onOk: async () => {
                  costdetail({...searchParams, receiveType: 1}).then(res =>{
                    if(res.total === 0) {
                      confirm({
                        title: '提示',
                        content: '无可标记操作的条目!',
                      })
                    } else {
                      confirm({
                        title: '提示',
                        content: `即将标记${res.total}条条目，是否继续操作？`,
                        onOk:async()=>{
                          const result = await quickMark()
                          if(result){
                            actionRef.current.reload();
                            handleSelectedRows([])
                            handleSelectedRowKeys([])
                          }
                        }
                      })
                    }
                  })
                }
              })
            }}>
              一键标记
            </Button>
          </AuthComponent>,
          <AuthComponent authCode="luggageCharts.cost.mark">
            <Button type="default" onClick={()=>{
              if (selectedRows.length === 0) {
                message.error("请选择需要取消标记的条目 ！")
              } else {
                let unuseful = selectedRows.filter(item => {return item.isFlag !== '标记'})
                confirm({
                  title: '提示',
                  content: `共选择${selectedRows.length}条需要取消标记的条目，${unuseful.length}条无效条目，是否继续进行取消标记操作？`,
                  cancelText: '取消',
                  okText: '确认',
                  onOk: async () => {
                    const result = await changeFlag(selectedRows, '0')
                    if(result){
                      actionRef.current.reload();
                      handleSelectedRows([])
                      handleSelectedRowKeys([])
                    }
                  }
                })
              }
            }}>
              取消标记
            </Button>
          </AuthComponent>,
          <AuthComponent authCode="luggageCharts.cost.summary">
            <Button type="default" onClick={handleTotal}>
              总计
            </Button>
          </AuthComponent>,
          <AuthComponent authCode="luggageCharts.cost.export">
            <Button icon="download" type="primary" onClick={handleExport}>
              导出
            </Button>
          </AuthComponent>,
          <AuthComponent authCode="luggageCharts.cost.diyExport">
            <Button icon="download" type="primary" onClick={handleCustomExport}>
              自定义导出
            </Button>
          </AuthComponent>
        ]}
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
        }}
        columns={columns}
        beforeSearchSubmit={beforeSearchSubmit}
        postData={data => {
          if (data.length === 0) {
            handleExportFlag(false)
          } else {
            handleExportFlag(true)
          }
          return data
        }}
        request={params => {
          let troubleshootArr = ['payBeginDate','payEndDate','isFlag','flightNo','org','dst','serviceCity','flightModel','flightType','paxName','tktNo','receiveType','applyCode','payStatus','applyStatus','isScene','payTypes'];
            if (isFirst) {
              isFirst = false;
              if (!params['beginDate'] && !params['endDate']) {
                params['beginDate'] = moment().format('YYYY-MM-DD')
                params['endDate'] = moment().format('YYYY-MM-DD')
                ref.current.setFieldsValue({
                  beginDate: moment(),
                  endDate: moment()
                })
              }
            }else{
              let otherParamsHavaValue = false;
              for (const key of troubleshootArr) {
                const element = params[key];
                if (element || element?.length > 0) {
                  otherParamsHavaValue = true;
                  break;
                }
              } 
              if (!otherParamsHavaValue) {
                if (!params['beginDate'] && !params['endDate']) {
                  params['beginDate'] = moment().format('YYYY-MM-DD')
                  params['endDate'] = moment().format('YYYY-MM-DD')
                  ref.current.setFieldsValue({
                    beginDate: moment(),
                    endDate: moment()
                  })
                }
              }

              if (!params.payBeginDate) {
                ref.current.setFieldsValue({
                  payBeginDate: ''
                })
              } else {
                params['payBeginDate'] = params.payBeginDate ? params.payBeginDate.format('YYYY-MM-DD') : '';
              }
              if (!params.payEndDate) {
                ref.current.setFieldsValue({
                  payEndDate: ''
                })
              } else {
                params['payEndDate'] = params.payEndDate ? params.payEndDate.format('YYYY-MM-DD') : '';
              }
    
              params.isFlag = params.isFlag && params.isFlag.join(',')
              params.flightModel = params.flightModel && params.flightModel.join(',')
              params.flightType = params.flightType && params.flightType.join(',')
              params.receiveType = params.receiveType && params.receiveType.join(',')
              params.payStatus = params.payStatus && params.payStatus.join(',')
              params.applyStatus = params.applyStatus && params.applyStatus.join(',')
              params.isScene = params.isScene && params.isScene.join(',')
              params.payTypes = params.payTypes && params.payTypes.join(',')
    
              params.compensationType='1'
            }
          setSearchParams(params)
          return costdetail(params)
        }}
      />
      </Spin>
      <TotalModal totalModalVisible={totalModalVisible} totalData={totalData} onCancel={()=>handleTotalModalVisible(false)}/>
      <CustomExportModal searchParams={searchParams} customExportModalVisible={customExportModalVisible} columns={columns} onCancel={()=>handleCustomExportModalVisible(false)}/>
    </div>
  );
};

export default Form.create()(DetailTable);
